<template>
  <div>
    <!-- placeholder="请输入订单名称" @on-search="crmSearch"  -->
    <c-r-m-list-head
      title="外勤板块"
      :crm-type="crmType"
      @on-search="crmSearch"
      @on-export="exportInfos"
    />
    <!-- v-empty="!crm.complete.index" xs-empty-icon="nopermission" xs-empty-text="暂无权限" -->
    <div class="crm-container">
      <!-- <flexbox v-if="selectionList.length > 0" class="selection-bar">
          <div class="selected—title">已选中<span class="selected—count">{{selectionList.length}}</span>项</div>
          <flexbox class="selection-items-box">
            <flexbox class="selection-item" @click.native="pickClick()">
              <img class="selection-item-icon" src="@/assets/img/selection_get.png" />
              <div class="selection-item-name">捡取</div>
            </flexbox>
          </flexbox>
        </flexbox>s
        </flexbox> -->
      <c-r-m-table-head
        ref="crmTableHead"
        crm-type="personnel"
        type="wo"
        :isSeas="true"
        @filter="handleFilter"
        @handle="handleHandle"
        @scene="handleScene"
      />
      <el-table
        class="n-table--border"
        id="crm-table"
        v-loading="loading"
        :data="list"
        :height="tableHeight"
        stripe
        border
        highlight-current-row
        style="width: 100%"
        :cell-style="cellStyle"
        @row-click="handleRowClick"
        @header-dragend="handleHeaderDragend"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          show-overflow-tooltip
          :fixed="index == 0"
          :prop="item.prop"
          :label="item.label"
          width="160"
          :formatter="fieldFormatter"
        >
          <template slot="header" slot-scope="scope">
            <div class="table-head-name">{{ scope.column.label }}</div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="check_status_info"
          label="操作"
          :resizable="false"
          width="340"
          align="center"
          fixed="right"
        >
          <template slot="header" slot-scope="scope">
            <div class="table-head-name">{{ scope.column.label }}</div>
          </template>
          <template slot-scope="scope">
            <div
              class="status_button"
              :style="getStatusStyle('2')"
              v-if="commission"
              @click="handleMoney(scope.row.assignfield_id, '填写提成')"
            >
              填写提成
            </div>
            <div
              class="status_button"
              :style="getStatusStyle('1')"
              v-if="fieldreception && scope.row.status == '待接收'"
              @click="handlePull(scope.row, 0)"
            >
              接收
            </div>
            <div
              class="status_button"
              :style="getStatusStyle('1')"
              v-if="fieldreception && scope.row.status == '未完结'"
              @click="handlePull(scope.row, 1)"
            >
              完结
            </div>
            <div
              class="status_button"
              :style="getStatusStyle('1')"
              @click="handleDivided(scope.row.assignfield_id, '操作记录')"
              v-if="recordelog"
            >
              操作记录
            </div>
            <div
              class="status_button"
              :style="getStatusStyle('1')"
              style="cursor: pointer"
              v-if="scope.row.status == '未完结' && addflow"
              @click="handleDivided(scope.row.assignfield_id, '跟进记录')"
            >
              填写跟进记录
            </div>
            <div
              class="status_button"
              :style="getStatusStyle('1')"
              style="cursor: pointer"
              v-if="scope.row.status == '未完结' && addflow"
              @click="handleTransfer(scope.row.assignfield_id)"
            >
              转单
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="56">
          <template slot="header" slot-scope="slot">
            <img src="@/assets/img/t_set.png" @click="handleTableSet" class="table-set" />
          </template>
        </el-table-column>
      </el-table>
      <div class="p-contianer">
        <span class="money-bar">
          总办件数量：{{ moneyPageData.documentsCount || "0.00" }} / 总提成金额：
          {{ moneyPageData.commissionPrice || "0.00" }} / 产品总数量：{{
            moneyPageData.productCount || "0.00"
          }}
        </span>
        <el-pagination
          class="p-bar"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          layout="slot, total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>
    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      :visible.sync="showDview"
      :crmType="rowType"
      :id="rowID"
      type="complete"
      @handle="handleHandle"
      class="d-view"
    />
    <fields-set
      :crmType="crmType"
      @set-success="setSave"
      :dialogVisible.sync="showFieldSet"
    />
    <teams-handle
      :crmType="crmType"
      :title="teamsTitle"
      :selectionList="selectionList"
      @handle="handleCallBack"
      :orderList="orderList"
      :contractId="contractId"
      :dialogVisible.sync="teamsDialogShow"
    />
    <el-dialog
      title="转移办理事项"
      :visible.sync="transferShow"
      width="500px"
      @close="closeTransfer"
    >
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 8px">选择外勤人员：</div>
        <xh-user-cell
          class="handle-item-content"
          :radio="true"
          placeholder="点击选择（单选）"
          ref="del"
          infoType="3"
          @value-change="outsideChage"
        />
      </flexbox>
      <div slot="footer">
        <el-button @click="closeTransfer">取 消</el-button>
        <el-button type="primary" @click="confirmTransfer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  personnelFieldreception,
  adminIndexAuthList,
  personnelRecordelog,
  personnelTransfer,
} from "@/api/common";
import { accountPicking } from "@/api/customermanagement/common";
import CRMAllDetail from "@/views/customermanagement/components/CRMAllDetail";
import { XhUserCell } from "@/components/CreateCom";
import table from "../mixins/table";
import TeamsHandle from "@/views/customermanagement/components/selectAccounting/TeamsHandle";

export default {
  /** 客户管理 的 订单列表 */
  name: "completeIndex",
  components: {
    XhUserCell,
    CRMAllDetail,
    TeamsHandle,
  },
  mixins: [table],
  data() {
    return {
      crmType: "personnel",
      contractId: "",
      assignfield_id: "",
      moneyData: null, //订单列表金额
      isSeas: true,
      teamsDialogShow: false,
      selectionList: [],
      orderList: [],
      teamsTitle: "",
      fieldreception: "",
      commission: "",
      addflow: false,
      recordelog: false,
      transferShow: false, // 转移办理事项弹窗
      user_id: null,
    };
  },
  computed: {
    moneyPageData() {
      // 未勾选展示订单总金额信息
      if (this.selectionList.length == 0 && this.moneyData) {
        return this.moneyData;
      } else {
        let sumMoney = 0.0;
        let unReceivablesMoney = 0.0;
        for (let index = 0; index < this.selectionList.length; index++) {
          const element = this.selectionList[index];
          // 2 审核通过的订单
          if (element.check_status == 2) {
            sumMoney += parseFloat(element.money);
            unReceivablesMoney += parseFloat(element.unMoney);
          }
        }
        return {
          sumMoney: sumMoney.toFixed(2),
          unReceivablesMoney: unReceivablesMoney.toFixed(2),
        };
      }
    },
  },
  created() {
    this.getAuth();
  },
  mounted() {},
  methods: {
    handleRecord() {},
    handleMoney(id, type) {
      this.contractId = id.toString();
      this.teamsTitle = type;
      this.teamsDialogShow = true;
    },
    handlePull(row, type) {
      this.$prompt("请输入备注", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          personnelFieldreception({
            status: type,
            assignfield_id: row.assignfield_id,
            remark: value,
          }).then((res) => {
            this.$message.success(res.data);
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 获取权限
    getAuth() {
      return new Promise((resolve, reject) => {
        adminIndexAuthList()
          .then((response) => {
            const data = response.data;
            this.fieldreception = data.crm.personnel
              ? data.crm.personnel.fieldreception
              : false;
            this.commission = data.crm.personnel ? data.crm.personnel.commission : false;
            this.addflow = data.crm.personnel ? data.crm.personnel.addflow : false;
            this.recordelog = data.crm.personnel ? data.crm.personnel.recordelog : false;
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    pickClick() {
      this.$confirm("确定要捡取该工单吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = this.selectionList.map((item) => {
            return item.contract_id;
          });
          accountPicking({
            contract_id: ids,
          })
            .then((res) => {
              this.$message.success(res.data);
            })
            .catch(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    handleDivided(id, type) {
      console.log(id, type, "handleDivided");
      this.contractId = id.toString();
      this.teamsTitle = type;
      personnelRecordelog({
        assignfield_id: id,
      })
        .then((res) => {
          this.teamsDialogShow = true;
          this.orderList = res.data;
        })
        .catch(() => {});
    },
    // 转移办理事项
    handleTransfer(id) {
      this.contractId = id.toString();
      this.transferShow = true;
    },
    /** 选择转单人员 */
    outsideChage(data) {
      console.log(data, "outsideChage");
      if (data.value.length > 0) {
        this.user_id = data.value[0].id;
      } else {
        this.user_id = null;
      }
    },
    // 关闭转移弹窗
    closeTransfer() {
      this.$refs.del.deleteuser(0);
      this.transferShow = false;
      this.user_id = null;
      this.contractId = "";
    },
    // 确认转移
    confirmTransfer() {
      if (!this.user_id) {
        this.$message.error("请选择转单人员");
        return;
      }
      personnelTransfer({
        assignfield_id: this.contractId,
        admin_user_id: this.user_id,
      })
        .then((res) => {
          this.$message.success(res.data);
          this.closeTransfer();
        })
        .catch(() => {});
    },
    // 子组件 回调的 结果
    handleCallBack(data) {
      this.$emit("handle", {
        type: data.type,
      });
    },
    /** 通过回调控制style */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "contract_name" || column.property === "contract_num") {
        return {
          color: "#3E84E9",
          cursor: "pointer",
        };
      } else {
        return "";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../styles/table.scss";

.money-bar {
  color: #99a9bf;
  line-height: 44px !important;
  position: absolute;
  left: 20px;
  top: 0;
}

/** 勾选操作 */
.selection-bar {
  font-size: 14px;
  height: 34px;
  color: #777;
  margin: 10px 16px;

  .selected—title {
    flex-shrink: 0;
    padding-right: 20px;
    border-right: 1px solid $--table-border-color;

    .selected—count {
      color: $xr-color-primary;
    }
  }
}

.selection-items-box {
  .selection-item {
    width: auto;
    padding: 15px;

    .selection-item-icon {
      display: block;
      margin-right: 5px;
      width: 15px;
      height: 15px;
    }

    .selection-item-name {
      cursor: pointer;
      color: #777;
    }

    .selection-item-name:hover {
      color: $xr-color-primary;
    }
  }
}
</style>
